const { Model, Schema } = require('../helps/model');
const { formatData } = require('../helps/tools');
// CREATE TABLE `robot_relation` (
//   `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
//   `robot_id` int(11) unsigned NOT NULL COMMENT '机器人id',
//   `user_id` int(11) unsigned NOT NULL COMMENT '用户id',
//   `type` tinyint(1) unsigned NOT NULL COMMENT '关系类型',
//   `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
//   `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
//   `delete_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
//   PRIMARY KEY (`id`),
//   KEY `robot` (`robot_id`) USING BTREE,
//   KEY `user` (`user_id`) USING BTREE
// ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='机器人关系表表';

const schema = new Schema({
  primary: 'id',
  create_time: true,
  update_time: true,
  soft_delete: true,
  auto_increment: true,
  fields: ['id', 'robot_id', 'user_id', 'type'],
  default: {},
});

export const model = new Model('robot_relation', schema);

/**
 * 查找
 * @param id
 * @returns {*}
 */
export function get(id) {
  return model.findByKey(id);
}

/**
 * 查找列表
 * @param ids
 * @returns {*}
 */
export function getIds(ids) {
  return model.findByQuery({
    where: [
      ['id', 'in', ids],
    ],
  });
}

/**
 * 创建
 * @param data
 * @returns {*}
 */
export function add(data) {
  return model.insert(formatData(schema.baseFields(), data));
}

/**
 * 更新
 * @param id
 * @param data
 * @returns {*}
 */
export function put(id, data) {
  return model.updateByKey(id, formatData(schema.baseFields(), data));
}

/**
 * 删除
 * @param id
 * @returns {*}
 */
export function del(id) {
  return model.deleteByKey(id);
}

/**
 * 列表分页
 * @param page
 * @param number
 * @returns {*}
 */
export function search(where, page = 1, number = 50, order = 'id', direction = 'desc') {
  return model.findListAndCount(where, page, number, `\`${order}\` ${direction}`);
}

export function list(page, number, order, direction) {
  return search([], page, number, order, direction);
}

export function unbind(robot_id, user_id) {
  return model.one({
    where: {
      robot_id,
      user_id,
    },
  }).then((row) => {
    if (!row) return null;
    return model.delete(row);
  });
}

export function bind(robot_id, user_id, type) {
  return model.insert({
    robot_id,
    user_id,
    type,
  });
}

export function all(robot_id, order = 'id', direction = 'desc') {
  return model.findByQuery({
    where: [
      ['robot_id', '=', robot_id],
    ],
    order: `\`${order}\` ${direction}`,
  });
}
